﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
using System.Collections.Generic;

namespace HZ.DrugTrade.Web.Admin.BidProdManage
{
    public partial class CustomGoodsDealCheck : BasePage
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //绑定下拉框
                BindSortList();
                BindProjectList();

                //绑定表单
                BindForm();

                //绑定类似产品信息
                BindGridView();
            }
        }

        /// <summary>
        /// 绑定产品分类下拉框
        /// </summary>
        private void BindSortList()
        {
            IBLL_Sort ibbs = Factory.IBLL_Sort();
            IList<Sort> Lsort = ibbs.GetAllSort(null);

            this.dplSort.DataTextField = "SortName";
            this.dplSort.DataValueField = "SortID";
            this.dplSort.DataSource = Lsort;
            this.dplSort.DataBind();

            ListItem item = new ListItem();
            item.Text = "==请选择产品分类==";
            item.Value = Constants.ALL_ITEM_VALUE;
            dplSort.Items.Insert(0, item);
        }

        /// <summary>
        /// 绑定项目下拉框
        /// </summary>
        private void BindProjectList()
        {
            int totalRecord;
            ProcurementProject procurementProject = new ProcurementProject();
            IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
            IList<ProcurementProject> projectList = ipb.GetProjectByWhere(procurementProject, 1, 0, out totalRecord);
            dplProject.DataSource = projectList;
            dplProject.DataTextField = "ProjectName";
            dplProject.DataValueField = "ProjectID";
            dplProject.DataBind();
        }

        protected bool GetAuditStatus(CustomGoods model)
        {
            if (CurrentAccount.GetUser().Org.Area.AreaID.Contains("0000"))
            {
                trZX.Visible = true;
                this.lblStatusMs.Text = model.AuditorMS;
                return model.AuditStatus != 3;
            }
            else
            {
                this.ckbProcure.Checked = false;
                this.ckbProcure.Enabled = false;

                return model.AuditStatusMS != 3;
            }
        }
        /// <summary>
        /// 绑定表单
        /// </summary>
        private void BindForm()
        {
            string id = Request.QueryString["ID"];
            if (!string.IsNullOrEmpty(id))
            {
                IBLL_CustomGoods cstCtrl = Factory.BLL_CustomGoods();
                CustomGoods model = cstCtrl.GetCustomGoodsByID(id);
                if (model != null)
                {
                    this.txtGoodsName.Text = model.GoodsName;
                    this.txtMaterial.Text = model.Material;
                    this.txtOutlookc.Text = model.Outlookc;
                    this.txtUnit.Text = model.Unit;
                    this.txtPackUnit.Text = model.PackUnit;
                    this.txtCompanyName.Text = model.CompanyName;
                    this.txtAuditNote.Text = model.AuditNote;
                    this.txtReason.Text = model.AuditNoteMS;//盟市审核备注
                    if (!CurrentAccount.GetUser().Org.Area.AreaID.Contains("0000")&&model.AuditStatus==3)
                    {
                        this.btnSave.Enabled = false;//中心审核通过的盟市不能在审了
                    }      
                  
                    if (this.dplSort.Items.FindByValue(model.SortID) != null)
                    {
                        this.dplSort.Items.FindByValue(model.SortID).Selected = true;
                    }
                    if (this.dplLevel.Items.FindByValue(model.QualityLevel) != null)
                    {
                        this.dplLevel.Items.FindByValue(model.QualityLevel).Selected = true;
                    }
                    this.txtLimitPrice.Text = model.LimitPrice.Value.ToString("F"); ;
                    this.lblNote.Text = model.Note;
                    if (model.SMMPrice != null)
                    {
                        this.lblSMMPrice.Text = model.SMMPrice.Value.ToString("F");
                    }
                    else
                    {
                        this.lblSMMPrice.Text = "0.00";
                    }

                }
                else
                {
                    PageError("产品信息不存在！", ReturnUrl);
                }
            }
            else
            {
                PageError("参数不正确！", ReturnUrl);
            }
        }

        /// <summary>
        /// 根据页面上的产品信息，查找出类似产品（条件：通用名，生产企业）
        /// 从系统产品库中查询
        /// </summary>
        private void BindGridView()
        {
            Model.Query.Goods goods = new HZ.DrugTrade.Model.Query.Goods();
            goods.Material = this.txtMaterial.Text.Trim();   //材质
            goods.Append = " GoodsName like '%" + this.txtGoodsName.Text.Trim().Replace("'", "") + "%'";

            goods.SortFields = " ProductName asc";

            int totalCount = 0;

            IBLL_Goods ig = Factory.BLL_Goods();

            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;                  //updated by lhl 2009-08-28
            //IList<Model.View.Goods> goodsList = ig.GetAllGoodsByWhere(goods, 1, 0, out totalCount);
            IList<Model.View.Goods> goodsList = ig.GetAllGoodsByWhere(goods, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;

            this.gvwBidDrug.DataSource = goodsList;
            this.gvwBidDrug.DataBind();

        }

         //<summary>
         //格式化产品属性
         //</summary>
         //<param name="obj"></param>
         //<returns></returns>
        public static string FormatDrugSource(object obj)         //add by lhl  2009-08-27
        {
            string status = "未知";
            if (obj != null)
            {
                                switch (Convert.ToInt16(obj))
                {
                    case 0: status = "<font color=black>限价竞价</font>";
                        break;
                    case 1: status = "<font color=red>重点监控</font>";
                        break;
                    case 2: status = "<font color=blue>自行采购</font>";
                        break;
                    //case 3: status = "<font color=gray><i>临时采购</i></font>";
                    case 3: status = "<font color=gray><i>备案采购</i></font>";
                        break;
                    case 4: status = "<font color=gray><i>基本药物</i></font>";
                        break;
                    case 5: status = "<font color=gray><i>中标产品</i></font>";
                        break;
                }
            }
            return status;
        }

        /// <summary>
        /// Gridview绑定时间 判断匹配的结果中有无完全一致的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwBidDrug_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string strGoodsName = DataBinder.Eval(e.Row.DataItem, "GoodsName").ToString();
                string strMaterial = DataBinder.Eval(e.Row.DataItem, "Material").ToString();
                string strOutlookc = DataBinder.Eval(e.Row.DataItem, "Outlookc").ToString();
                string strFactor = DataBinder.Eval(e.Row.DataItem, "Factor").ToString();
                string strUnit = DataBinder.Eval(e.Row.DataItem, "Unit").ToString();
                string strCompanyName_SC = DataBinder.Eval(e.Row.DataItem, "CompanyName_SC").ToString();

                if (strGoodsName == txtGoodsName.Text.Trim() && strMaterial == txtMaterial.Text.Trim() &&
                    strOutlookc == txtOutlookc.Text.Trim() &&
                    strUnit == txtUnit.Text.Trim() && strCompanyName_SC == txtCompanyName.Text.Trim())
                {

                    e.Row.Attributes["style"] = "color:red;";
                    
                    //   HZ.Web.WebUtil.Alert("系统查找到精确匹配的数据，只能拒绝审核通过！", this);
                    //this.ddlType.SelectedValue = "1";//设置不通过
                    //this.ddlType.Enabled = false;
                    //this.rblSource.SelectedValue = "3";//设置未中标
                    //this.rblSource.Enabled = false;
                    //this.ckbProcure.Visible = false;
                    //this.dplProject.Visible = false;
                    this.txtReason.Text = "此产品已在采购产品列表存在";
                }
            }
        }

        /// <summary>
        /// 提交打回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DenyAudit()
        {
            string id = Request.QueryString["ID"];
            CustomGoods model = new CustomGoods();
            model.ID = Convert.ToInt32(id);
            model.SubmitToUS = 2;//已拒绝可修改
            if (CurrentAccount.GetUser().Org.Area.AreaID.Contains("0000"))
            {
                model.AuditStatus = 4;
                model.Auditor = CurrentAccount.GetUser().UserID;
                model.AuditNote = txtReason.Text.Trim();
                model.AuditTime = DateTime.Now;
            }
            else
            {
                model.AuditStatusMS = 4;
                model.AuditorMS = CurrentAccount.GetUser().Org.OrgName;
                model.AuditNoteMS = txtReason.Text.Trim();
                model.AuditTimeMS = DateTime.Now;
            }

            IBLL_CustomGoods cstCtrl = Factory.BLL_CustomGoods();
            int result = cstCtrl.UpdateCustomGoods(model);
            if (result == 1)
            {
                PageInfo("产品申请已被拒绝！", "CustomGoodsCheckList.aspx");
            }
            else
            {
                PageError("操作出错请联系管理员！", "CustomGoodsCheckList.aspx");
            }

        }

        /// <summary>
        /// 通过审核，并将产品信息写入产品库
        /// 数据以页面数据为准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfirmAudit()
        {
            //检查产品中是否有重复产品
            IBLL_Goods goodCtrl = Factory.BLL_Goods();
            Model.Query.Goods where = new HZ.DrugTrade.Model.Query.Goods()
            {
                GoodsName = txtGoodsName.Text.Trim(),
                Material = txtMaterial.Text.Trim(),
                Outlookc = txtOutlookc.Text.Trim(),
                Unit = txtUnit.Text.Trim(),
                CompanyName_SC = txtCompanyName.Text.Trim(),
            };
            //有类似的产品也可以审核通过，但是不加到采购目录 by zdc
            //int temp;
            //IList<HZ.DrugTrade.Model.View.Goods> goodsList = goodCtrl.GetAllGoodsByWhere(where, 1, 0, out temp);
            //if (goodsList.Count > 0)
            //{
            //    PageError("药库中有重复的数据！请重新检查数据。", this.Request.RawUrl);
            //    return;
            //}

            //将产品添加到产品库
            string id = Request.QueryString["ID"];
            CustomGoods model = new CustomGoods()
            {
                ID = Convert.ToInt32(id),
                Source = (rblSource.SelectedValue == "2") ? 2 : 3,//备案产品或未采购产品
                //
                GoodsName = txtGoodsName.Text.Trim(),
                Material = txtMaterial.Text.Trim(),
                Outlookc = txtOutlookc.Text.Trim(),
                Unit = txtUnit.Text.Trim(),
                CompanyName = txtCompanyName.Text.Trim(),
                SortID = dplSort.SelectedValue,
                QualityLevel = dplLevel.SelectedValue,
                LimitPrice = string.IsNullOrEmpty(txtLimitPrice.Text.Trim()) ? 0 : new HZ.Common.ConvertHelper(txtLimitPrice.Text.Trim()).ToDecimal
            };
            if (CurrentAccount.GetUser().Org.Area.AreaID.Contains("0000"))
            {
                model.AuditStatus = 3;
                model.Auditor = CurrentAccount.GetUser().UserID;
                model.AuditNote = txtReason.Text.Trim();
                model.AuditTime = DateTime.Now;
            }
            else
            {
                model.AuditStatusMS = 3;
                model.AuditorMS = CurrentAccount.GetUser().Org.OrgName;
                model.AuditNoteMS = txtReason.Text.Trim();
                model.AuditTimeMS = DateTime.Now;
            }
            string goodsID;
            IBLL_CustomGoods cstCtrl = Factory.BLL_CustomGoods();
            if (CurrentAccount.GetUser().Org.Area.AreaID.Contains("0000"))
            {
                int result = cstCtrl.AuditCustomGoods(model, out goodsID);
                //执行操作，添加新的采购产品
                if (result == 1)
                {
                    if (this.ckbProcure.Checked)
                    {
                        ProcureCatalog procureCatalog = new ProcureCatalog();
                        View_Procurecatalog_TB vpt = new View_Procurecatalog_TB();

                        procureCatalog.GoodsID = goodsID;
                        procureCatalog.ProcurePrice = Convert.ToDecimal(txtLimitPrice.Text.Trim());
                        procureCatalog.ProjectID = dplProject.SelectedItem.Value;
                        procureCatalog.SortSource = (rblSource.SelectedValue == "2") ? 2 : 3; //备案产品或未采购产品
                        procureCatalog.CompanyIDs_PS = "";
                        procureCatalog.CompanyNames_PS = "";
                        procureCatalog.IsUsing = true;
                        procureCatalog.IsFlowing = true;
                        procureCatalog.AddTime = DateTime.Now;

                        //系统升级之后，目录View_Procurecatalog_TB add by zdc
                        vpt.GoodsID = goodsID;
                        vpt.ProcurePrice = Convert.ToDecimal(txtLimitPrice.Text.Trim());
                        vpt.ProjectID = dplProject.SelectedItem.Value;
                        vpt.SortSource = (rblSource.SelectedValue == "2") ? 2 : 3; //备案产品或未采购产品
                        vpt.ProcureStartTime = DateTime.Parse("2011-1-1 10:06:09");
                        vpt.ProcureEndTime = DateTime.Parse("2011-12-31 10:06:09");
                        vpt.IsUsing = true;
                        vpt.IsFlowing = true;
                        vpt.AddTime = DateTime.Now;
                        vpt.GoodsName = model.GoodsName;
                        vpt.Qualitylevel = model.QualityLevel;
                        vpt.Material = model.Material;
                        vpt.SortID = model.SortID;
                        vpt.ShortName = model.ShortName;
                        vpt.Outlookc = model.Outlookc;
                        vpt.Unit = model.Unit;
                        vpt.PackUnit = model.PackUnit;
                        vpt.PinyinCode = HZ.Common.zhHansUtil.GetSpellHeads(model.GoodsName).ToUpper();
                        vpt.CompanyName_SC = model.CompanyName;
                        vpt.CompanyID_SC = cstCtrl.Getcompanyid_SC(model.CompanyName);
                        vpt.Price = 0;
                        
                        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
                        result = ipb.AddProcureCatalog(procureCatalog,vpt);
                    }
                }

                if (result == 1)
                {
                    string success = "产品审核成功！\n◎已将此药加入到基础产品库。\n";
                    if (this.ckbProcure.Checked) { success += "◎已将此药加入到采购目录。"; }
                    PageInfo(success, "CustomGoodsCheckList.aspx");
                }
                else
                {
                    PageError("操作出错，请联系管理员！", "CustomGoodsCheckList.aspx");
                }
            }
            else
            {
                int result = cstCtrl.AuditCustomGoods(model);
                if (result == 1)
                {
                    //string success = "产品审核成功！\n◎已将此药加入到基础产品库。\n";
                    //if (this.ckbProcure.Checked) { success += "◎已将此药加入到采购目录。"; }
                    string success = "产品审核成功！";
                    PageInfo(success, "CustomGoodsCheckList.aspx");
                }
                else
                {
                    PageError("操作出错，请联系管理员！", "CustomGoodsCheckList.aspx");
                }
            }
        }



        /// <summary>
        /// 
        /// 对于非中标药采购限价计算规则
        ///  >575 -75
        ///  <=575  /1.15
        ///
        /// </summary>
        /// <param name="goodsModel"></param>
        /// <returns></returns>
        private decimal GetProcurePrice(decimal limitPrice)
        {
            if (limitPrice <= 575)
            {
                return (limitPrice / (decimal)1.15);
            }
            else
            {
                return (limitPrice - 75);
            }
        }

        /// <summary>
        /// 执行审核操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.ddlType.SelectedValue == "0")
            {
                //通过审核
                ConfirmAudit();
            }
            else
            {
                //拒绝通过
                DenyAudit();
            }

        }

        /// <summary>
        /// 查询类似产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //复位操作类型
            this.ddlType.Enabled = true;

            AspNetPager1.CurrentPageIndex = 1;

            //重新查询
            BindGridView();
        }

        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
    }
}
